﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;

using FRL.DebtChased.Extensions;

namespace FRL.DebtChased.Repository
{

	/// <summary>
	/// Extensions to the ErrorLog model
	/// </summary>
	public partial class ErrorLog
	{

		/////////////////////////////////////////////////////////////
		// Static operations

		public static void DeleteErrorLog( DebtChasedEntities ent, int iDeleteErrorLogId )
		{

			// Compose sql and excecute
			string strSql;
			if (iDeleteErrorLogId != -1)
				strSql = string.Format("DELETE FROM tbErrorLog WHERE fdErrorLogId={0}",iDeleteErrorLogId);
			else
				strSql = "DELETE FROM tbErrorLog";
			ent.ExecuteStoreCommand(strSql);

		}

		public static void Add(DebtChasedEntities ent, string strAction, Exception x, int? iUserId)
		{

			// Note: Must add error using direct sql

			// Compose an error description
			string strError;
			if (x == null)
				strError = "No exception information";
			else
			{
				strError = x.Message;
				if (x.InnerException != null)
					strError += x.InnerException;
			}

			// Compose parameters
			string strParameters = string.Empty;

			try
			{

				// Compose sql statement
				StringBuilder sb = new StringBuilder();
				sb.Append("INSERT INTO tbErrorLog (fdAction,fdError,fdUserId,fdTimestamp,fdParameters) VALUES (");
				sb.AppendFormat("{0},", strAction.ToDBString());
				sb.AppendFormat("{0},", strError.ToDBString());
				if (iUserId.HasValue)
					sb.AppendFormat("{0},", iUserId);
				else
					sb.Append("NULL,");
				sb.AppendFormat("{0},", DateTime.Now.ToDBString());
				sb.AppendFormat("{0})", strParameters.ToDBString());
				ent.ExecuteStoreCommand(sb.ToString());

			}
			catch
			{
#if DEBUG
				Debug.Assert(false);
#endif // #if DEBUG

				// Waste the error

			}

		}

	}

}
